Strict

#TEXTFILES="*.txt|*.xml|*.json|*.lua"

Import mojo
Import monkeylua
Import monkeylua.mojolua

Function Main:Int()
	New LuaApp
	Return 0
End

Class LuaApp Extends App
	Field state:LuaState
	Field uselua:Bool = True
	
	Method OnCreate:Int()
		SetUpdateRate(60)
		state = New LuaState
		RegisterMojoLua(state) ' Must call this to register all the Mojo functions and constants in Lua
		LoadLua()
		Return 0
	End

	Method OnUpdate:Int()
		If KeyHit(KEY_TAB) Then uselua = Not uselua
		If KeyHit(KEY_F5) Then LoadLua()
		If KeyHit(KEY_ESCAPE) Then Error ""
		
		If uselua Then state.DoString("update()")
		
		Return 0
	End

	Method OnRender:Int()
		FPSCounter.Update()
		Cls(0,0,0)
		If uselua Then
			DrawText("Press TAB to toggle Lua calls (currently on)", 0, 15)
		Else
			DrawText("Press TAB to toggle Lua calls (currently off)", 0, 15)
		End
		DrawText("Press F5 to reload Lua script", 0, 30)
		
		If uselua Then state.DoString("render()")
		
		SetColor(255,255,255)
		FPSCounter.Draw()
		Return 0
	End
	
	Method LoadLua:Void()
		If state.DoFile("data/game.lua") <> LUA_OK Then Print state.ToString(-1)
	End
End

Class FPSCounter
	Global fpsCount:Int
	Global startTime:Int
	Global totalFPS:Int

	Function Update:Void()
		If Millisecs() - startTime >= 1000
			totalFPS = fpsCount
			fpsCount = 0
			startTime = Millisecs()
		Else
			fpsCount+=1
		End
	End

	Function Draw:Void(x% = 0, y% = 0, ax# = 0, ay# = 0)
		DrawText("FPS: " + totalFPS, x, y, ax, ay)
	End
End
